# -*- coding: utf-8 -*
from django import forms
from mysitebbs.models import PostModel,TopicModel

class PostForm(forms.ModelForm):
    #fid = models.IntegerField(max_length=8,default=0)
	#tid = models.IntegerField(max_length=8,default=0)
	#first = models.SmallIntegerField(max_length=1,default=0)
	#subject = models.CharField(max_length=80)
	#message = models.TextField()
	#anonymous = models.SmallIntegerField(max_length=1,default=0)
	#tags = models.CharField(max_length=200,blank=True)

	class Meta:
		model = PostModel
		fields = ('message',)
	
	#def save(self,request):
	#	model = PostModel(self)
	#	model.save()
	#	return post
		
class ThreadForm(forms.ModelForm):

	class Meta:
		model = TopicModel
		fields = ('forum','author','author_name','subject','lastposter',)
		
	def save(self):
		md = TopicModel(fid = self['fid'].value(),
						author = self['author'].value(),
						authorid = self['authorid'].value(),
						subject = self['subject'].value(),
						lastposter = self['lastposter'].value(),
						)
		md.save()
		self.tid = md.tid#不符合Form格式

class NewPostForm(forms.ModelForm):
	subject = forms.CharField(max_length=255)
	
	class Meta:
		model = PostModel
		fields = ('message',)
	
	def __init__(self,*args,**kwargs):
		self.user = kwargs.pop('user',None)
		self.forum = kwargs.pop('forum',None)
		self.topic = kwargs.pop('topic',None)
		self.ip = kwargs.pop('ip',None)
		#self.position = kwargs.pop('ip',None)
		super(NewPostForm,self).__init__(*args,**kwargs)
		
		
	def save(self):
		if self.forum:#新帖子
			topic = TopicModel(forum=self.forum,
								author=self.user,
								author_name=self.user.username,
								subject=self.cleaned_data['subject'],
								lastposter=self.user)
			topic.save()
		else:#回帖
			topic = self.topic
			topic.replies = topic.replies+1
			topic.save()
			
		post = PostModel(topic=topic,
						author=self.user,
						author_name=self.user.username,						
						authorip=self.ip,
						message=self.cleaned_data['message'],
						position=topic.replies)
		post.save()
						